package com.arsn.myf.quartz.service.impl;

import com.arsn.myf.quartz.entity.ScheduledJob;
import com.arsn.myf.quartz.enums.ScheduledStatus;
import com.arsn.myf.quartz.mapper.ScheduledJobMapper;
import com.arsn.myf.quartz.service.ScheduledJobService;
import com.arsn.myf.quartz.vo.ScheduledJobVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.quartz.CronTrigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.List;
import com.arsn.myf.quartz.config.ScheduleManager;

/**
 * 定时任务接口实现层
 * @author zhongrj
 * @since 2022-03-07
 */
@Service
public class ScheduledJobServiceImpl extends ServiceImpl<ScheduledJobMapper, ScheduledJob> implements ScheduledJobService {

    @Autowired
    private ScheduleManager scheduleManager;

    /**
     * 初始化定时任务,系统一启动即执行
     */
    @PostConstruct
    public void init(){
        List<ScheduledJob> list = list();
        if (list.size()>0) {
            list.forEach(scheduledJob -> {
                //获取 triggerKey
                CronTrigger cronTrigger = scheduleManager.getCronTrigger(scheduledJob);
                if (null == cronTrigger) {
                    //创建定时任务
                    scheduleManager.createScheduledJob(scheduledJob);
                }else if(ScheduledStatus.NORMAL.getType().equals(scheduledJob.getStatus())){
                    //恢复定时任务
                    scheduleManager.resumeJob(scheduledJob);
                }else if(ScheduledStatus.PAUSE.getType().equals(scheduledJob.getStatus())){
                    //暂停任务
                    scheduleManager.pauseJob(scheduledJob);
                }
            });
        }
    }



    /**
     * 自定义定时任务的分页数据
     * @param page
     * @param scheduledJob
     * @return
     */
    @Override
    public IPage<ScheduledJobVO> selectPageScheduledJobList(Page<ScheduledJobVO> page, ScheduledJobVO scheduledJob) {
        return baseMapper.selectPageScheduledJobList(page, scheduledJob);
    }
}
